﻿using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Threading;
using MongoDB.Bson;

namespace MongoDB
{
    public partial class InstallServer : Form
    {
        formmain mf;
        string config;
        Form f;
        public InstallServer(formmain _mf, string _config, Form _f)
        {
            mf = _mf;
            config = _config;
            f = _f;
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            Thread thread = new Thread(new ThreadStart(DoSomething));
            thread.Start();
        }

        public void DoSomething()
        {
            DoInstall();
            Thread.Sleep(1000);
            DoStartService();
            Thread.Sleep(1000);
            if (mf.cbtype.Text=="ReplicaSet")
            {
                DoClusters();
            }
            btnclose.Enabled = true;
            picloading.Visible = false;
            labmsg.Text = "MongoDB安装完毕！";
        }

        private void DoInstall()
        {
            labmsg.Text = "正在安装服务...";
            var path = string.Format(@"{0}\bin\mongod.exe ", Application.StartupPath);
            Process p = new Process();
            p.StartInfo.Arguments = string.Format(" --config {0} --install", config);
            p.StartInfo.FileName = path;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            p.StandardInput.Flush();
            txtlog.Text += p.StandardOutput.ReadToEnd();
            txtlog.Text += "\r\n";
            p.WaitForExit();
            p.Close();
            txtlog.Text += "完成";
            txtlog.Text += "\r\n";
        }

        private void DoStartService()
        {
            labmsg.Text = "正在启动服务...";
            Process p = new Process();
            p.StartInfo.FileName = "CMD.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine("net start MongoDB");
            p.StandardInput.Flush();
            p.StandardInput.WriteLine("exit");
            txtlog.Text += p.StandardOutput.ReadToEnd();
            txtlog.Text += "\r\n";
            p.WaitForExit();
            p.Close();
            txtlog.Text += "完成";
            txtlog.Text += "\r\n";
        }

        private void DoClusters()
        {
            labmsg.Text = "正在安装群集服务...";
            if (!((ReplicaSet)f).ckbismaster.Checked)
            {
                string host = mf.txtlocalhost.Text;
                string port = mf.txtport.Text;
                MongoClientSettings mcs = new MongoClientSettings();
                mcs.Server = new MongoServerAddress(host, Convert.ToInt32(port));//
                MongoClient c = new MongoClient(mcs);
                var s = c.GetServer();
                var db = s.GetDatabase("admin");
                var list = new BsonArray();
                list.Add(new BsonDocument(){
                        {"_id",1},
                        {"host",string.Format("{0}:{1}",host,port)}
                    });
                int i = 2;
                foreach (var item in ((ReplicaSet)f).list)
                {
                    var mb = new BsonDocument(){
                        {"_id",i},
                        {"host",item}
                    };
                    list.Add(mb);
                    i++;
                }
                BsonDocument doc = new BsonDocument(){
                    {"_id",((ReplicaSet)f).txtrsname.Text},
                    {"members",list}
                };
                BsonDocument commenddoc = new BsonDocument() { { "replSetInitiate",doc } };
                var commend = new CommandDocument(commenddoc);
                try
                {
                    var res = db.RunCommand(commend);
                    if (res.Ok)
                    {
                        txtlog.Text += "群集设置：success!!";
                        txtlog.Text += "\r\n";
                    }
                    else
                    {
                        txtlog.Text += "群集设置：error!!";
                        txtlog.Text += "\r\n";
                        txtlog.Text += res.ErrorMessage;
                        txtlog.Text += "\r\n";
                    }
                }
                catch (Exception e)
                {
                    txtlog.Text += e.Message;
                    txtlog.Text += "\r\n";
                }
            }
        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            this.Close();
            mf.Close();
        }

        private void InstallServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            mf.Close();
        }
    }

}
